#ifndef OSMTILESOURCE_H
#define OSMTILESOURCE_H

#include "MapTileSource.h"
#include "MapGraphics_global.h"
#include <QSet>
#include <QHash>
#include <QSettings>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

//Forward declaration so that projects that import us as a library don't necessarily have to use QT += network
class QNetworkReply;

class MAPGRAPHICSSHARED_EXPORT OSMTileSource : public MapTileSource
{
    Q_OBJECT
public:
    enum OSMTileType
    {
        OSMTiles,
        TDTTiles,
        TOTAL_TYPES
    };
    static OSMTileType tileTypes[TOTAL_TYPES];
    static QString getTileTypeName(OSMTileType tileType);
public:
    explicit OSMTileSource(OSMTileSource::OSMTileType tileType = TDTTiles);
    virtual ~OSMTileSource();

    virtual QPointF ll2qgs(const QPointF& ll, quint8 zoomLevel) const;

    virtual QPointF qgs2ll(const QPointF& qgs, quint8 zoomLevel) const;

    virtual quint64 tilesOnZoomLevel(quint8 zoomLevel) const;

    virtual quint16 tileSize() const;

    virtual quint8 minZoomLevel(QPointF ll);

    virtual quint8 maxZoomLevel(QPointF ll);

    virtual QString name() const;

    virtual QString tileFileExtension() const;

protected:
    virtual void fetchTile(quint32 x,
                           quint32 y,
                           quint8 z);

private:
    OSMTileSource::OSMTileType _tileType;

    //Set used to ensure a tile with a certain cacheID isn't requested twice
    QSet<QString> _pendingRequests;

    //Hash used to keep track of what cacheID goes with what reply
    QHash<QNetworkReply *, QString> _pendingReplies;
    
    // 配置文件相关
    QString _configFilePath;
    QString _tdtKey; // 天地图API密钥
    
    // MBTiles相关
    bool _useMBTiles; // 是否使用MBTiles文件
    QString _mbtilesFilePath; // MBTiles文件路径
    QSqlDatabase _mbtilesDB; // MBTiles数据库连接
    
    // 从MBTiles获取瓦片的私有方法
    QImage* getTileFromMBTiles(quint32 x, quint32 y, quint8 z);
    
signals:
    
public slots:
    // 设置配置文件路径
    void setConfigFilePath(const QString &configPath);
    // 从配置文件重新加载设置
    void reloadSettings();

private slots:
    void handleNetworkRequestFinished();
    
};

#endif // OSMTILESOURCE_H
